package com.ustcinfo.ishare.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by Shinelon on 2017/12/26.
 * 根据类名 获取 该类的属性
 */
public class ClassFieldsCollector {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClassFieldsCollector.class);

    /**
     * 获取 类的属性 和 属性值
     * @param object
     * @return
     */
    public Map getFiledsInfo(Object object){
        List list = new ArrayList();
        Map map = new HashMap();
        Field[] fields = object.getClass().getDeclaredFields();
        for (int i=0;i<fields.length;i++){
//            map.put(fields[i].getName(),fields[i].getType().getSimpleName()+"="+getFieldValueByFieldName(fields[i].getName().toString(),object));
            map.put(fields[i].getName(),getFieldValueByFieldName(fields[i].getName().toString(),object));
        }
        return map;
    }

    private Object getFieldValueByFieldName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    public static void main(String[] args) {
//        Blog blog = new Blog("0", "123","123","123", 123456789l, "1", "hehe", "meme","wowo",1,"he");
//        new ClassFieldsCollector().getFiledsInfo(blog);
//        Map map = new ClassFieldsCollector().getFiledsInfo(blog);
//
//        Iterator keys = map.entrySet().iterator();
//        while (keys.hasNext()) {
//            Map.Entry entry = (Map.Entry) keys.next();
//            System.out.println(entry.getKey() + "===" + map.get(entry.getKey().toString()));
//        }
//    }
}
